package java6681.data;

import java.io.*;

/**
 * @author Junichiro
 * @description
 * @date 2021-05-16 19:01
 **/

public class StudyObjectData6681 {
    public static void main(String[] args) {
        writeStudent6681();
        readStudent();
    }
    private static void writeStudent6681() {
        /*步骤一：确定输出的文件（目的地）*/
        File file = new File("write" + File.separator + "student6681.dat");
        /*步骤二：创建指向文件的对象流*/
        /*步骤三：写对象*/
        try ( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));){
            out.writeObject(new Student6681("张舒婷",22));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void readStudent() {
        /*步骤一：确定输入的源文件*/
        File file = new File("write"+File.separator+"student6681.dat");
        /*输入时文件必须存在*/
        if (!file.exists()){
            System.out.println("文件不存在！");
            return;
        }
        /*步骤二：创建指向文件的对象流*/
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))){
            /*步骤三：读数据*/
            Object obj = in.readObject();
            System.out.println(obj);
            Student6681 stu = (Student6681) obj;
            System.out.println("姓名="+stu.getName()+",年龄="+stu.getAge());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
class Student6681 implements Serializable {
    private static final long serialVersionUID = 1l;
    private String name;
    private int age;

    public Student6681(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return String.format("name=%s,age=%d",name,age);
    }
}
